//
//  UITableView+Reusable.swift
//  
//
//  Created by tangbl93 on 2021/2/5.
//

import UIKit

public extension UITableView {
    
    // MARK: - Cell register and reuse
    
    /// Register cell nib
    func yx_registerCellNib<T: UITableViewCell>(_ aClass: T.Type) {
        let name = aClass.yx_reuseIdentifier
        let nib = UINib(nibName: name, bundle: nil)
        self.register(nib, forCellReuseIdentifier: name)
    }
    
    /// Register cell class
    func yx_registerCellClass<T: UITableViewCell>(_ aClass: T.Type) {
        let name = aClass.yx_reuseIdentifier
        self.register(aClass, forCellReuseIdentifier: name)
    }
    
    /// Reusable Cell
    func yx_dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath?) -> T {
        let name = T.yx_reuseIdentifier
        
        var reusableCell: T?
        if let indexPath = indexPath {
            reusableCell = dequeueReusableCell(withIdentifier: name, for: indexPath) as? T
        } else {
            reusableCell = dequeueReusableCell(withIdentifier: name) as? T
        }
        
        guard let cell = reusableCell else {
            fatalError("\(name) is not registed")
        }
        return cell
    }
    
    // MARK: - HeaderFooter register and reuse
    
    /// Register cell nib
    func yx_registerHeaderFooterNib<T: UIView>(_ aClass: T.Type) {
        let name = aClass.yx_reuseIdentifier
        let nib = UINib(nibName: name, bundle: nil)
        self.register(nib, forHeaderFooterViewReuseIdentifier: name)
    }
    
    /// Register cell class
    func yx_registerHeaderFooterClass<T: UIView>(_ aClass: T.Type) {
        let name = aClass.yx_reuseIdentifier
        self.register(aClass, forHeaderFooterViewReuseIdentifier: name)
    }
    
    /// Reusable Cell
    func yx_dequeueReusableHeaderFooter<T: UIView>(_ aClass: T.Type) -> T {
        let name = T.yx_reuseIdentifier
        guard let cell = dequeueReusableHeaderFooterView(withIdentifier: name) as? T else {
            fatalError("\(name) is not registed")
        }
        return cell
    }
}
